package com.example.springboot.v2.mapping;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;

/**
 * 定义 请求映射的规则
 *
 * @author by Mr. Li 2021/1/30 17:31
 */

public class ApiVersionCondition implements RequestCondition<ApiVersionCondition> {

    /*一般版本号为：v1 v0.1 v0.01 这种格式*/
    @Getter
    private String apiVersion;

    public ApiVersionCondition(String apiVersion) {
        this.apiVersion = apiVersion;
    }

    /**
     * 合并
     *
     * @param other
     * @return
     */
    @Override
    public ApiVersionCondition combine(ApiVersionCondition other) {
        return new ApiVersionCondition(other.getApiVersion());
    }

    /**
     * 获取 匹配的 条件
     * 所有的请求都会进入判断
     *
     * @param request 请求
     * @return ApiVersionCondition
     */
    @Override
    public ApiVersionCondition getMatchingCondition(HttpServletRequest request) {
        final String header = request.getHeader("Api-Version");
        // 截取版本号
        if (StrUtil.isNotBlank(header)) {
            final Integer integer = splitVersion(header);
            if (integer >= splitVersion(this.apiVersion)) // 如果请求的版本号大于等于配置版本号， 则满足
                return this;
        }
        // 查看当前请求参数中是否存在版本参数
        final String requestURI = request.getRequestURI();
        final String[] split = requestURI.split("/");
        for (String s : split) {
            if (s.startsWith("v")) {
                // 请求参数中存在版本指定
                final Integer integer = splitVersion(s);
                if (integer >= splitVersion(this.apiVersion)) // 如果请求的版本号大于等于配置版本号， 则满足
                {
                    //TODO 将版本信息设置到请求头中
                    return this;
                }
            }
        }
        return null;
    }

    private Integer splitVersion(String apiVersion) {
        final String sub = StrUtil.sub(apiVersion, 1, apiVersion.length());
        return Convert.toInt(Convert.toDouble(sub) * 100);
    }

    @Override
    public int compareTo(ApiVersionCondition other, HttpServletRequest request) {
        // 优先匹配最新的版本号
        return (splitVersion(other.getApiVersion()) - splitVersion(this.apiVersion));
    }

    public static void main(String[] args) {
        String apiVersion = "v0.01";
        apiVersion = StrUtil.sub(apiVersion, 1, apiVersion.length());
        System.out.println(apiVersion);
        System.out.println(Convert.toDouble(apiVersion));
    }
}
